<template>
  <div class="deploy">
    <div class="cardTop">创建一个新数据集</div>
    <el-card class="elCard">
      <div class="left">
        <ul class="leftUl">
          <li :class="changeClass" class="leftLi">
            <div class="circle">
              <img src="../../assets/image/圆圈.svg" alt="" />
            </div>
            <div class="text">基础信息</div>
          </li>
          <li class="leftLi2">
            <div class="circle">
              <img src="../../assets/image/圆圈.svg" alt="" />
            </div>
            <div class="text">文件下载</div>
            <div class="textBottom" @click="mouseupHandle()">
              <img :src="isCreate ? xiala2 : xiala" alt="" />
              已上传文件
            </div>
          </li>
          <li class="leftLi3" :class="changeClass">
            <div class="circle3">
              <img src="../../assets/image/圆圈.svg" alt="" />
            </div>
          </li>
        </ul>
      </div>
      <div class="elForm">
        <el-form :model="form" :rules="rules" label-width="120px">
          <el-form-item
            label="数据集名称:"
            prop="cont_name"
            style="font-weight: bold"
          >
            <el-input v-model="form.cont_name" />
          </el-form-item>

          <el-form-item
            label="数据集类型:"
            style="font-weight: bold"
            prop="dataset_type"
          >
            <el-radio-group v-model="form.radio">
              <el-radio
                style="padding-bottom: 7px; margin-left: 15px"
                label="train"
                size="large"
                >训练集</el-radio
              >
              <el-radio style="padding-bottom: 7px" label="test" size="large"
                >测试集</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="数据集描述:" style="font-weight: bold">
            <el-input
              placeholder="请输入数据集描述"
              maxlength="10"
              show-word-limit
              type="text"
              v-model="form.desc"
            />
          </el-form-item>
          <el-form-item>
            <!-- 原始的上传 -->
            <el-upload
              class="upload-demo"
              drag
              action="http://192.168.11.222:9009/buckets/langport-test/browse/ZGF0YXNldHMv"
              multiple
              style="margin-left: 15px; width: 80%"
              @change="putFiles"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">拖动上传或者<em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip">
                  文件不能大于500kb<br />支持fbx/obj/glb格式单文件的上传
                </div>
              </template>
            </el-upload>

            <!-- 上传 -->
            <!-- <input ref="input" type="file" @change="putFiles" /> -->
          </el-form-item>
          <div class="high" v-if="isHighShow">
            <el-button type="primary" @click="downloadFileFromS3()"
              >下载</el-button
            >

            <el-button type="primary" @click="download()">后台下载</el-button>
          </div>
          <el-form-item class="elButton">
            <el-button type="primary" @click="onSubmit">确认</el-button>
            <el-button @click="cancel">取消</el-button>

            <!-- <el-button type="primary" @click="submitForm">上传</el-button> -->
            <!-- <el-button @click="cancel">取消创建</el-button> -->
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElRadio,
  ElInput,
  ElRadioGroup,
  ElUpload,
  ElSelect,
  ElOption,
  ElMessage,
  ElIcon,
  ElCard,
  ElCheckbox
} from 'element-plus'
import { ref, reactive, computed, onMounted } from 'vue'
import {
  getGather,
  downloadGather,
  createGather,
  delGather
} from '../../api/gather.js'
import xiala2 from '../../assets/image/上拉.png'
import xiala from '../../assets/image/下拉.png'
import axios from 'axios'
import { Bufferfrom, createClient } from 'minio-vite-js'
import { saveAs } from 'file-saver'
import { useRouter } from 'vue-router'
const router = useRouter()

// 全局s3client对象
let s3Client = null

const fileName = ref('')

/**
 * 创建并更新全局s3client:
 * 具体的endPoint ,port ,acesskey ,secretKey使用你自己项目中的值
 * createClient接口的调用方法与minio中的new Minio.Client使用方法相同
 */
function setS3Client () {
  try {
    s3Client = createClient({
      endPoint: '192.168.11.222',
      // port: 9009,之前端口号是这
      port: 9000,
      useSSL: false, // 将 useSSL 设置为 false
      accessKey: 'minioadmin',
      secretKey: 'minioadmin'
    })

    console.log('s3Client', s3Client)
  } catch (err) {
    console.error('连接minio失败', err)
  }
}

/**
 * 上传文件
 * 有了s3Client对象之后，调用其他接口就完全和minio官网的使用方式相同了
 * 注意这里使用了Bufferfrom接口，因为直接在vite项目中使用Buffer.from()会报错，所以我把这个功能也单独封装了一下
 */
// 原input上传成功版
// function putFiles (event) {
//   var f = event.target.files[0]

//   // 调试代码，输出文件对象
//   console.log('fileName.value:', f.name)

//   if (!(f instanceof Blob)) {
//     console.error('Invalid file object:', f)
//     return
//   }

//   let reader = new FileReader()
//   reader.onload = function (e) {
//     try {
//       if (!s3Client) {
//         throw new Error('MinIO client is not initialized')
//       }

//       let res = e.target.result // ArrayBuffer
//       let buf = Bufferfrom(res) // Buffer

//       console.log('buf', buf)

//       s3Client.bucketExists('langport-test', function (err, exists) {
//         if (err) {
//           console.error('Error checking bucket existence:', err)
//         } else {
//           console.log('Bucket exists:true表示连接成功,并储存桶存在', exists)
//         }
//       })

//       s3Client.listBuckets(function (err, buckets) {
//         if (err) {
//           console.error('Error listing buckets:', err)
//         } else {
//           console.log('Buckets:列出所有的存储桶', buckets)
//         }
//       })
//       s3Client.putObject('langport-test', f.name, buf, function (err, data) {
//         if (err) {
//           console.error('Failed to upload object:', err)
//         } else {
//           console.log('上传完成', data)
//         }
//       })
//     } catch (error) {
//       console.error('minio上传文件失败:', error)
//     }
//   }

//   reader.readAsArrayBuffer(f)
// }

let isMessageShown = false // 让文件上传s3成功后,只弹一次

function putFiles (file) {
  var f = file.raw
  fileName.value = file.raw.name
  if (!(f instanceof Blob)) {
    console.error('Invalid file object:', f)
    return
  }

  let reader = new FileReader()
  reader.onload = function (e) {
    try {
      if (!s3Client) {
        throw new Error('MinIO client is not initialized')
      }

      let res = e.target.result // ArrayBuffer
      let buf = Bufferfrom(res) // Buffer

      s3Client.putObject(
        'langport-test',
        fileName.value,
        buf,
        {
          'x-amz-meta-usage-count': '1'
        },
        function (err, data) {
          if (err) {
            console.error('Failed to upload object:', err)
          } else {
            if (!isMessageShown) {
              // 判断是否已经显示了弹窗
              isMessageShown = true // 更新标志变量
              ElMessage({
                message: '成功上传到s3数据库',
                type: 'success'
              })
            }
          }
        }
      )

      s3Client.statObject(
        'langport-test',
        fileName.value,
        function (err, stat) {
          if (err) {
            console.error('Error listing buckets:', err)
          } else {
            console.log('使用次数:', stat['x-amz-meta-usage-count'])
            console.log('使用次数:', stat.metaData['x-amz-meta-usage-count'])
          }
        }
      )
    } catch (error) {
      console.error('minio上传文件失败:', error)
    }
  }

  reader.readAsArrayBuffer(f)
}

function downloadFileFromS3 () {
  if (!s3Client) {
    console.error('MinIO client is not initialized')
    return
  }
  try {
    s3Client.getObject('langport-test', fileName.value, function (err, data) {
      if (err) {
        console.error('Failed to download object:', err)
      } else {
        var blob = new Blob([data.Body], { type: data.ContentType })
        saveAs(blob, fileName.value)
      }
    })
  } catch (error) {
    console.error('从minio下载文件失败:', error)
  }
}

// 在组件加载时设置s3Client
setS3Client()

const form = ref({
  cont_name: '',
  radio: '',
  desc: ''
})

const isHighShow = ref(false) // 高级配置显示
const isCreate = ref(false) // 下拉图片切换

const checked1 = ref(false)
const checked2 = ref(false)

//高级配置 显示事件
const mouseupHandle = () => {
  isCreate.value = !isCreate.value
  isHighShow.value = !isHighShow.value
}

const handleUpload = (res, file, fileList) => {
  console.log('文件上传成功', res)
}

//高级配置 样式更改
const changeClass = computed(() => {
  if (isCreate.value) {
    return 'leftLi isCreateTrue'
  } else {
    return 'leftLi'
  }
})

// 点击取消
const cancel = () => {
  router.go(-1)
}

const rules = reactive({
  cont_name: [
    { required: true, message: '请输入正确的英文名字', trigger: 'blur' }
  ],
  dataset_type: [
    { required: true, message: '请选择数据集类型', trigger: 'blur' }
  ]
})

const download = () => {
  downloadGather({ model_name: 'belle_multiturn' })
    .then(res => {
      console.log('后端的下载返回', res)
    })
    .catch(error => {
      console.error(error)
    })

  console.log('提交了表单')
}

// 确定
const onSubmit = () => {
  createGather({
    name: form.value.cont_name,
    d_type: form.value.radio,
    num_uses: 0,
    create_time: '2024-02-01',
    tag: form.value.desc
  })
    .then(res => {
      console.log('gather res', res)
      // 处理请求成功的响应
      // if (res.msg === 200) {
      //   form.value = res.data
      //   imageList.value = res.data.imgname
      //   modelList.value = res.data.cont_name
      // }
      ElMessage({
        showClose: true,
        message: '新建数据集成功',
        type: 'success'
      })
    })
    .catch(error => {
      // 处理请求错误
      console.error(error)
    })

  console.log('提交了表单')
}
</script>

<style lang="less" scoped>
.deploy {
  padding: 30px 60px 0 60px;

  .cardTop {
    margin-bottom: 30px;
    color: #27264d;
    font-size: 32px;
    opacity: 0.85;
    display: flex;
  }
  .elCard {
    .left {
      width: 300px;
      .leftUl {
        img {
          width: 20px;
          height: 20px;
        }
        .text {
          margin-left: 15px;
          color: #27264d;
          font-weight: 500;
          font-size: 16px;
          line-height: 24px;
          letter-spacing: 0;
          opacity: 0.85;
        }

        .leftLi {
          display: flex;
          .circle {
            position: relative;
          }
          .circle::after {
            content: '';
            position: absolute;
            top: 60%;
            left: 50%;
            transform: translate(-50%, 0);
            width: 2px;
            height: var(--circle-height, 480px);
            background-color: #75b7ff;
          }
        }
        .leftLi2 {
          display: flex;
          margin-top: 400px;
          align-items: center;
          .textBottom {
            padding-left: 10px;
            color: rgba(112, 114, 121, 0.85);
            font-size: 15px;
            cursor: pointer;
            img {
              width: 15px;
              height: 12px;
            }
          }
        }
        .leftLi3 {
          display: flex;
          .circle3 {
            position: relative;
            top: var(--circle-top, 40px);
          }
        }
        .isCreateTrue {
          --circle-height: 540px;
          --circle-top: 90px;
        }
      }
    }
    .elForm {
      width: 1000px;

      .elButton {
        :deep(.el-form-item__content) {
          display: flex;
          justify-content: space-between;
          margin-top: 30px;
        }
      }
    }
  }

  :deep(.el-card__body) {
    display: flex;
  }
}
</style>
